<template>
  <div class="notifications-page">
    <van-nav-bar
        title="通知消息"
        left-text="返回"
        left-arrow
        @click-left="handleBack"
        right-text="全部已读"
        :right-text-style="hasUnread ? 'color: #1989fa;' : 'color: #c8c9cc;'"
        @click-right="markAllRead"
    />

    <div class="notifications-content" ref="contentRef">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <van-loading type="spinner" color="#1989fa" />
        <p class="loading-text">加载中...</p>
      </div>

      <!-- 通知列表 -->
      <div v-else>
        <van-swipe-cell
            v-for="msg in notifications"
            :key="msg.id"
            :name="msg.id"
        >
          <!-- 正常显示的通知项 -->
          <template #left>
            <!-- 这里可以放置其他内容，如果需要的话 -->
          </template>

          <div
              class="notification-item"
              :class="{ 'unread': !msg.isRead }"
              @click="goToMessageDetail(msg.id, msg.type,msg.status)"
          >
            <div class="notification-avatar">
              <van-icon :name="getIconName(msg.type)" :color="getIconColor(msg.type)" />
            </div>
            <div class="notification-content">
              <div class="notification-title">
                <span>{{ msg.title || '系统通知' }}</span>
                <van-badge v-if="!msg.isRead" class="unread-badge" dot />
              </div>
              <div class="notification-message" :title="msg.message">
                {{ truncatedMessage(msg.message) }}
              </div>
              <div class="notification-time">{{ formatDate(msg.createdAt) }}</div>
            </div>
          </div>

          <!-- 右侧的删除按钮 -->
          <template #right>
            <van-button
                square
                type="danger"
                text="删除"
                class="delete-button"
                @click="deleteNotificationById(msg.id, $event)"
            />
          </template>
        </van-swipe-cell>

        <div v-if="notifications.length === 0" class="empty-notifications">
          <van-empty description="暂无通知消息" />
        </div>

        <!-- 加载更多 -->
        <div v-if="loadingMore" class="loading-more-container">
          <van-loading type="spinner" size="16" color="#1989fa" />
          <span style="margin-left: 8px;">加载中...</span>
        </div>

        <!-- 没有更多数据 -->
        <div v-if="notifications.length > 0 && !hasMore && !loadingMore" class="no-more-data">
          没有更多数据了
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { NavBar, Badge, Empty, Toast, Loading, Button } from 'vant';
import { useNotificationStore } from '@/store/notification';

const router = useRouter();
const notificationStore = useNotificationStore();

// 使用store中的notifications数据
const notifications = computed(() => notificationStore.notifications);
const loading = computed(() => notificationStore.loading);
const loadingMore = computed(() => notificationStore.loadingMore);
const hasMore = computed(() => notificationStore.hasMore);

// 用于追踪滚动元素
const contentRef = ref<HTMLElement>();

// 检查是否有未读通知
const hasUnread = computed(() => notificationStore.notifications.some(n => !n.isRead));

// 返回上一页
const handleBack = () => {
  router.back();
};

// 标记所有消息为已读
const markAllRead = () => {
  if (hasUnread.value) {
    notificationStore.markAllAsRead();
    Toast('已全部标记为已读');
  }
};

// 根据通知类型获取图标名称
const getIconName = (type: string) => {
  const iconMap: Record<string, string> = {
    system: 'setting',
    order: 'shopping-cart-o',
    comment: 'comment',
    activity: 'gift',
    health: 'underway'
  };
  return iconMap[type] || 'setting';
};

// 根据通知类型获取图标颜色
const getIconColor = (type: string) => {
  const colorMap: Record<string, string> = {
    system: '#1989fa',
    order: '#ff976a',
    comment: '#722ed1',
    activity: '#ff5777',
    health: '#07c160'
  };
  return colorMap[type] || '#1989fa';
};

// 格式化日期
const formatDate = (date: Date) => {
  const now = new Date();
  const notificationDate = new Date(date);
  const diffTime = Math.abs(now.getTime() - notificationDate.getTime());
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

  if (diffDays === 0) {
    // 今天
    const hours = notificationDate.getHours().toString().padStart(2, '0');
    const minutes = notificationDate.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  } else if (diffDays === 1) {
    // 昨天
    return '昨天';
  } else if (diffDays < 7) {
    // 一周内
    return `${diffDays}天前`;
  } else {
    // 超过一周显示具体日期
    const month = (notificationDate.getMonth() + 1).toString().padStart(2, '0');
    const day = notificationDate.getDate().toString().padStart(2, '0');
    return `${month}-${day}`;
  }
};

// 跳转到消息详细页面
const goToMessageDetail = (notificationId: number, type: string, status: number) => {
  notificationStore.markAsRead(notificationId); // 标记为已读
  if (type === 'order') {
    router.push({ name: 'OrderDetail', params: { id: notificationId, status: status } });
  } else if (type === 'comment') {
    router.push({ name: 'CommentDetail', params: { id: notificationId, status: status } });
  } else {
    router.push({ name: 'MessageDetail', params: { id: notificationId } });
  }
};

// 截断过长的消息内容
const truncatedMessage = (message: string) => {
  const maxLength = 100; // 设置最大显示长度
  if (message && message.length > maxLength) {
    return message.substring(0, maxLength) + '...';
  }
  return message;
};

// 删除通知
const deleteNotificationById = async (notificationId: number, event: Event) => {
  event.stopPropagation(); // 阻止事件冒泡

  try {
    // 显示确认对话框（可选，推荐使用 van-dialog）
    // 这里使用简单的 confirm 作为示例
    if (confirm('确定要删除这条通知吗？')) {
      console.log({ message: '删除中...', forbidClick: true });

      // 调用 store 中的删除方法
      await notificationStore.deleteNotification(notificationId);

      console.log('删除成功');
      // 如果需要，可以在这里执行其他逻辑，如刷新列表
    }
  } catch (error) {
    console.error('删除通知失败:', error);
  }
};
</script>

<style scoped lang="scss">
.notifications-page {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.notifications-content {
  flex: 1;
  overflow-y: auto;
  padding: 0;
  margin-bottom: 0px; // 根据实际需求调整
}

.notification-item {
  display: flex;
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  align-items: flex-start;
  transition: background-color 0.2s;
}

.notification-item:active {
  background-color: #f5f5f5;
}

.notification-item.unread {
  background-color: #fff9f0;
}

.notification-avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background-color: #f8f8f8;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-title {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
  font-weight: 500;
  font-size: 16px;
  color: #323233;
}

.notification-message {
  font-size: 14px;
  color: #646566;
  margin-bottom: 4px;
  line-height: 1.4;
  word-break: break-word;
  display: -webkit-box;
  -webkit-line-clamp: 1; /* 限制显示的行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.notification-time {
  font-size: 12px;
  color: #c8c9cc;
}

.unread-badge {
  margin-left: 8px;
}

.empty-notifications {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
}

/* 加载更多样式 */
.loading-more-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
  color: #999;
  font-size: 14px;
}

.no-more-data {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  color: #999;
  font-size: 14px;
}

/* 删除按钮样式 */
.delete-button {
  height: 100%;
  border: none;
  background-color: #ee0a24;
  color: #fff;
  font-size: 16px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>